package com.study.talk.app.chat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;


import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.study.talk.R;
import com.study.talk.adapter.ChatMessageListAdapter;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.app.friend.UserInfoActivity;
import com.study.talk.databinding.ActivityChatBinding;
import com.study.talk.entity.MessageRecord;
import com.study.talk.entity.UserInfo;
import com.study.talk.net.NetApi;
import com.study.talk.netty.NettyClient;
import com.study.talk.netty.message.request.MessageRequest;
import com.study.talk.netty.message.response.MessageSelfResponse;
import com.study.talk.util.AppExecutor;
import com.study.talk.util.DateUtil;
import com.study.talk.util.FileUtil;
import com.study.talk.util.GsonInstance;
import com.study.talk.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class ChatActivity extends BaseActivity implements View.OnClickListener {

    private UserInfo friendInfo;

    private List<MessageRecord> messageRecordList;

    private ChatMessageListAdapter adapter;

    private ActivityResultLauncher<PickVisualMediaRequest> selectPhoto;
    private ActivityResultLauncher<Uri> takePhoto;

    private LinearLayoutManager linearLayoutManager;

    private ActivityChatBinding activityChatBinding;
    private final String TAG = "ChatActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        activityChatBinding = ActivityChatBinding.inflate(getLayoutInflater());
        setContentView(activityChatBinding.getRoot());

        friendInfo = GsonInstance.instance.fromJson(getIntent().getStringExtra("data"), UserInfo.class);
        selectPhoto = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                uploadImage(FileUtil.getPathFromUri(ChatActivity.this, uri));
            }
        });
        takePhoto = registerForActivityResult(new ActivityResultContracts.TakePicture(), result -> {
            if (result) {
                uploadImage(FileUtil.getPathFromUri(ChatActivity.this, uri));
            }
        });
        setSupportActionBar(activityChatBinding.chatToolbar);
        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.chat_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        friendInfo = GsonInstance.instance.fromJson(intent.getStringExtra("data"), UserInfo.class);
        getSupportActionBar().setTitle("与好友" + friendInfo.getNickName() + "聊天");
        setData();
    }

    public void toBottom() {
        linearLayoutManager.scrollToPositionWithOffset(adapter.getItemCount() - 1, Integer.MIN_VALUE);
        //activityChatBinding.chatListView.setSelection(activityChatBinding.chatListView.getBottom());
    }

    @SuppressLint("NonConstantResourceId")
    private void initView() {
        getSupportActionBar().setTitle("与好友" + friendInfo.getNickName() + "聊天");
        activityChatBinding.chatToolbar.setNavigationOnClickListener(v -> finish());
        activityChatBinding.chatToolbar.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.chat_menu_user_info -> {
                    Intent intent = new Intent(getApplicationContext(), UserInfoActivity.class);
                    intent.putExtra("userId", friendInfo.getId());
                    startActivity(intent);
                }
                case R.id.chat_other_setting ->
                        ToastUtil.showToast(getApplicationContext(), "功能开发中...");
                default -> finish();
            }
            return true;
        });

        activityChatBinding.chatMsgSendBt.setOnClickListener(view -> {
            if (checkInput(activityChatBinding.chatMsgEdit, "不能发送空消息或者空格内容哦")) return;
            String content = editTrim(activityChatBinding.chatMsgEdit);
            MessageRequest messageRequest = new MessageRequest(friendInfo.getId(), content, 0);
            messageRequest.setDateTime(DateUtil.getCurrentTime());
            NettyClient.sendMessage(messageRequest);
        });

        setData();


        activityChatBinding.chatBottomMenuAudio.setOnClickListener(this);
        activityChatBinding.chatBottomMenuEmoji.setOnClickListener(this);
        activityChatBinding.chatBottomMenuOther.setOnClickListener(this);

        activityChatBinding.chatBottomMenuImage.setOnClickListener(view -> showSelectPhotoDialog(selectPhoto, takePhoto));
    }

    private void setData() {
        /*new Thread(() -> {
            messageRecordList = getApp().db.messageDao().getListByChatId(friendInfo.getId());
            adapter = new ChatMessageListAdapter(messageRecordList, this);

            runOnUiThread(() -> {
                linearLayoutManager = new LinearLayoutManager(this);
                linearLayoutManager.setStackFromEnd(true);
                activityChatBinding.chatListView.setLayoutManager(linearLayoutManager);
                activityChatBinding.chatListView.setAdapter(adapter);
                toBottom();
            });
        }).start();*/
        AppExecutor.getInstance().FILE_IO().execute(() -> {
            messageRecordList = getApp().db.messageDao().getListByChatId(friendInfo.getId());
            adapter = new ChatMessageListAdapter(messageRecordList, this);

            /*runOnUiThread(() -> {
                linearLayoutManager = new LinearLayoutManager(this);
                linearLayoutManager.setStackFromEnd(true);
                activityChatBinding.chatListView.setLayoutManager(linearLayoutManager);
                activityChatBinding.chatListView.setAdapter(adapter);
                toBottom();
            });*/
            AppExecutor.getInstance().MAIN_HANDLER().post(() -> {
                linearLayoutManager = new LinearLayoutManager(this);
                linearLayoutManager.setStackFromEnd(true);
                activityChatBinding.chatListView.setLayoutManager(linearLayoutManager);
                activityChatBinding.chatListView.setAdapter(adapter);
                toBottom();
            });
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN, priority = 10)
    public void onMessageSelfResponse(MessageSelfResponse messageSelfResponse) {
        dismissLoadingDialog();
        if (messageSelfResponse.getSuccess()) {
            //清空输入框
            setText(activityChatBinding.chatMsgEdit, "");

            MessageRecord messageRecord = new MessageRecord(getApp().userInfo, messageSelfResponse, true, friendInfo.getId());
            //new Thread(() -> getApp().db.messageDao().insertMessage(messageRecord)).start();
            AppExecutor.getInstance().FILE_IO().execute(() -> getApp().db.messageDao().insertMessage(messageRecord));
            messageRecordList.add(messageRecord);

            //通知RecycleView更新
            adapter.notifyItemInserted(messageRecordList.size());
            toBottom();
        } else {
            ToastUtil.showToast(ChatActivity.this, messageSelfResponse.getReason());
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageResponse(MessageRecord messageRecord) {
        messageRecordList.add(messageRecord);
        //通知RecycleView更新
        adapter.notifyItemInserted(messageRecordList.size());
        toBottom();
        //new Thread(() -> getApp().db.messageDao().insertMessage(messageRecord)).start();
        AppExecutor.getInstance().FILE_IO().execute(() -> getApp().db.messageDao().insertMessage(messageRecord));
    }

    public void uploadImage(String path) {
        NetApi.uploadImage(path, ChatActivity.this, data -> {
            MessageRequest messageRequest = new MessageRequest(friendInfo.getId(), data, 1);
            messageRequest.setDateTime(DateUtil.getCurrentTime());
            NettyClient.sendMessage(messageRequest);
            showLoadingDialog();
        }, msg -> runOnUiThread(() -> ToastUtil.showToast(ChatActivity.this, msg)));
    }

    @Override
    public void onClick(View v) {
        ToastUtil.showToast(this, "功能开发中...");
    }
}